package com.faryangsh.algorithm.basicfor1;

import org.junit.Assert;

/**
 * 1.3.2 定容栈
 *
 * Created by 杨志远 on 2017/8/12
 * email faryangsh@163.com.
 */
public class FixedCapacityStackOfString<T> {
    int forwardIndex;
    T[] items;
    int size;
    public void push(T obj){
//        Assert.assertNotEquals("stack is full",size,forwardIndex);
        // stak is full,then enlarge twice size
        if (forwardIndex ==size) resize(2*size);
        items[forwardIndex++]=obj;
    }

    /*public T dequeue(){
        return items[--forwardIndex];
    }*/

    public T pop(){
        T item = items[--forwardIndex];
        items[forwardIndex]=null;
        //useful length of stack  lower then 1/4 stack'size,then halve stack
        if (forwardIndex >0 && forwardIndex ==size/4) resize(size/2);
        return item;
    }


    public boolean isEmpty(){
        return forwardIndex ==0;
    }

    public FixedCapacityStackOfString(int size){
        items=(T[]) new Object[size];
        this.size=size;
    }

    private void resize(int max){
        Assert.assertTrue("modified size lower than current forwardIndex",max> forwardIndex);
        T[] temp=(T[]) new Object[max];
        for (int i = 0; i < size; i++)
            temp[i]=items[i];
        items=temp;
        size=max;
    }

    public static void main(String[] args) {
        FixedCapacityStackOfString stack = new FixedCapacityStackOfString(3);
        stack.push("1");
        stack.push("2");
        stack.push("3");
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        stack.push("4");
        stack.push("5");
        stack.push("6");
        stack.push("7");
        System.out.println(stack.pop());
    }

}

